#define _CRT_SECURE_NO_WARNINGS

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#define NUM 1024
#define SIZE 64
#define SEP " "
//#define Debug 1
char cwd[NUM];
char enval[NUM];
int lastcode = 0; //exit code
// get environment variable
const char* getUsername()
{
    const char* name = getenv("USER");
    if (name) return name;
    else return "none";
}
const char* getHostname()
{
    const char* host = getenv("HOSTNAME");
    if (host) return host;
    else return "none";
}
const char* getCwd()
{
    const char* cwd = getenv("PWD");
    if (cwd) return cwd;
    else return "none";
}
int getUserCommand(char* command, int num)
{
    printf("[%s@%s %s]#", getUsername(), getHostname(), getCwd());
    char* r = fgets(command, num, stdin); // still have a '\' in the end when you input
    if (r == NULL) return -1;
    // remove the '\n'
    command[strlen(command) - 1] = '\0'; // input's input  at least have a '\n', so dont't will crossed
#ifdef Debug 
    printf("%s", usercommand); //test
#endif
    return strlen(command);
}
void commandSplit(char* in, char* out[])
{
    int argc = 0;
    out[argc++] = strtok(in, SEP);
    while (out[argc++] = strtok(NULL, SEP));
#ifdef Debug
    for (int i = 0; out[i]; i++)
    {
        printf("%d:%s\n", i, out[i]);
    }
#endif
}
int execute(char* argv[])
{
    pid_t id = fork();
    if (id < 0) return -1;
    else if (id == 0) // child 
    {
        // process replace   exec command
        execvp(argv[0], argv);
        exit(1);
    }
    else // father
    {
        int status = 0;
        pid_t rid = waitpid(id, &status, 0);
        if (rid > 0) { // wait success
            lastcode = WEXITSTATUS(status);
        }
    }
    return 0;
}
void cd(char* path)
{
    chdir(path);
    char tmp[NUM];
    getcwd(tmp, sizeof tmp);
    sprintf(cwd, "PWD=%s", tmp);
    putenv(cwd);
}
int doBulidin(char* argv[])
{
    if (strcmp(argv[0], "cd") == 0)
    {
        char* path = NULL;
        if (argv[1] == NULL) path = ".";
        else path = argv[1];
        cd(path);
        return 1;
    }
    else if (strcmp(argv[0], "export") == 0)
    {
        if (argv[1] == NULL) return 1;
        strcpy(enval, argv[1]);
        putenv(enval);
        return 1;
    }
    else if (strcmp(argv[0], "echo") == 0)
    {
        char* val = argv[1] + 1; // $PATH  $?
        if (strcmp(val, "?") == 0) {
            printf("%d\n", lastcode);
            lastcode = 0;
        }
        else {
            printf("%s\n", val);
        }
        return 1;
    }
    return 0;
}
int main()
{
    while (1) {
        char usercommand[NUM]; // store user's input
        char* argv[SIZE]; // a table store commands
        // getUsercommand and print command_line prompt
        int n = getUserCommand(usercommand, sizeof(usercommand));
        if (n <= 0) continue; // if only have a '\n'
        // split commands and store in array
        commandSplit(usercommand, argv);
        n = doBulidin(argv); // check or do bulidin_command
        if (n) continue;
        execute(argv);
    }
}
